<?php
namespace app\admin\model;

use app\common\service\RedisComm;

class Chip extends Base{

    protected $name = 'chip';

    public function delStockChip($id=0){
        $this->where(['sid'=>$id])->delete();
    }

    public function chipDetail($where=[]){
        return $this->where($where)->find();
    }

    public function updateChip($arr=[], $arrData=[]){
    	$data = [];
    	$data['average_cost'] = !empty($arrData['average_cost']) ? trim($arrData['average_cost']) : 0 ;
    	$data['seventy_percent'] = !empty($arrData['seventy_percent']) ? trim($arrData['seventy_percent']) : 0 ;
    	$data['ninety_percent'] = !empty($arrData['ninety_percent']) ? trim($arrData['ninety_percent']) : 0 ;
    	$data['market_concentration'] = !empty($arrData['market_concentration']) ? trim($arrData['market_concentration']) : 0 ;
    	$this->where(['sid'=>$arr['sid'], 'stock_code'=>$arr['stock_code']])->update($data);
    }

    public function addChip($arr=[]){
        if(!empty($arr['sid']) && !empty($arr['stock_code'])){
            if(self::where(['sid'=>$arr['sid'], 'stock_code'=>$arr['stock_code']])->find() == null){
                $this->insert(['sid'=>$arr['sid'], 'stock_code'=>$arr['stock_code']]);
            }
        }
    }

    public static function Detail(int $sid = 0, string $stockCode = '', string $jys = ''){
        
        if($sid == 0){
            return [];
        }
        $k = 'stock:'.$jys.$stockCode.':chip_detail';
        $result = RedisComm::Get($k) ?? null;
        if(!empty($result)){

            return json_decode($result, true);
        }else{

            $resultChip = self::where('sid', '=', $sid)->find();
            if(!empty($resultChip)){
                $resultChip = $resultChip->toArray();
                RedisComm::Set($k, json_encode($resultChip), 86400);
                return $resultChip;
            }
        }
        return [];
    }

    public static function getChip(int $sid = 0, string $stockCode = '', string $jys = ''){
        
        if($sid == 0){
            return [];
        }
        $k = 'stock:'.$jys.$stockCode.':chip';
        $result = RedisComm::Get($k) ?? null;
        if(!empty($result)){

            return $result;
        }else{

            $resultChip = self::where(['sid'=>$sid])->find();
            if(!empty($resultChip)){
                $resultChip = $resultChip->toArray();
                $resultChip['seventy_percent'] = (float)$resultChip['seventy_percent'];
                if(!empty($resultChip['seventy_percent']) && $resultChip['seventy_percent'] > 0){
                    RedisComm::Set($k, $resultChip['seventy_percent'], 86400);
                    return $resultChip['seventy_percent'];
                }
            }
        }
        return 0;
    }
}